//
//  ImageLoader.swift
//  Jock
//
//  Created by HD on 15/3/19.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

//图片缓存协议
protocol ImageCacheProtocol {
    
    //获取缓存图片的路径
    func loadCachePath() -> String
}

//图片加载
class ImageLoader {
    
    ///加载图片
    class func loadImage(urlString: String, imageCacheDir cacheDir: String! = nil, placeHolderName placeHolder: String! = nil, loadImageView imageView: UIImageView! = nil, callBack callback: ((image: UIImage) -> Void)! = nil) {
        let url = NSURL(string: urlString)
        let cacheFilename = url!.lastPathComponent
        var cachePath: String!
        var image: UIImage!
        var placeHolderImage: UIImage!
        if placeHolder != nil {
           placeHolderImage = UIImage(named: placeHolder)
        }
        if cacheDir != nil {
            cachePath = FileUtil.getCachePath(cacheDir, fileName: cacheFilename!)
            image = FileUtil.loadImageFromPath(cachePath)
        }
        if image != nil {
            if imageView != nil {
                imageView.image = image
            }
            if callback != nil {
                callback(image: image)
            }
        } else {    // 网络获取image
            if placeHolderImage != nil && imageView != nil {
                imageView.image = placeHolderImage
            }
            ThreadUtil.childThread({ () -> Void in
                let data = NSData(contentsOfURL: url!)
                if data != nil {
                    image = UIImage(data: data!)
                    if image != nil && cachePath != nil {
                        FileUtil.imageCacheToPath(cachePath, image: data!)
                    }
                }
                ThreadUtil.mainThread({ () -> Void in
                    if imageView != nil {
                        imageView.image = image
                    }
                    if callback != nil {
                        callback(image: image)
                    }
                })
            })
        }
    }
}